package com.niiwoo.civet.mobile.lanmao.handler;

import java.util.Collections;
import java.util.Date;

import com.niiwoo.civet.account.constant.RedisKeyConstant;
import lombok.Getter;
import lombok.Setter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.account.dto.request.CompanyAccountRequestDTO;
import com.niiwoo.civet.account.dto.response.AccountBaseResponse;
import com.niiwoo.civet.account.enums.CompanyAccountStatusEnums;
import com.niiwoo.civet.account.service.AccountCompanyDubboService;
import com.niiwoo.civet.account.service.AccountDubboService;
import com.niiwoo.civet.user.dto.request.OrganizationRequestDTO;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.tripod.lanmao.enums.LanMaoGatewayServiceNameEnum;
import com.niiwoo.tripod.provider.exception.BizException;

@Component
public class ChangeCompanyInfomationNotifyHandler implements LanMaoNotifyHandler{
	
	 public static final Logger logger = LoggerFactory.getLogger(ChangeCompanyInfomationNotifyHandler.class);
	 
	 @Reference(version="1.0.0")
	 private AccountDubboService accountDubboService;
	 
	 @Reference(version="1.0.0")
	 private OrganizationDubboService organizationDubboService;
	 
	 @Reference(version="1.0.0")
	 private AccountCompanyDubboService accountCompanyDubboService;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Override
	public boolean supports(String serviceName) {
		return LanMaoGatewayServiceNameEnum.ENTERPRISE_INFORMATION_UPDATE.name().equals(serviceName);
	}

	@Override
	public HandleResult handle(JSONObject json) {
		logger.info("修改企业资料回调处理###报文###data={}",json.toString());
		BankCardMobileNoGatewayResponse response=json.toJavaObject(BankCardMobileNoGatewayResponse.class);
		if(response.isCallSuccess()&&response.isBusinessSuccess()){
			CompanyAccountRequestDTO reqDto=new CompanyAccountRequestDTO();
			OrganizationRequestDTO orgInfoReqDto=null;
			reqDto.setAccountNo(response.getPlatformUserNo());
			reqDto.setUpdateMangerId(1L);//系统修改默认id
			reqDto.setUpdateTime(new Date());

			if (response.getReviewStatus().equals(CompanyAccountStatusEnums.PASSED.name())
					|| response.getReviewStatus().equals(CompanyAccountStatusEnums.REFUSED.name())) {
				String redisKey = RedisKeyConstant.UPLOADED_COMPANY_INFO_KEY_PREFIX + response.getPlatformUserNo();
				redisTemplate.delete(redisKey);
			}

			if(response.getReviewStatus().equals(CompanyAccountStatusEnums.AUDIT.name())||
					response.getReviewStatus().equals(CompanyAccountStatusEnums.REFUSED.name())){//审核中、审核失败修改存管账户的状态
				reqDto.setAuditStatus(CompanyAccountStatusEnums.getByName(response.getReviewStatus()).getStatus());
				
			}else if(response.getReviewStatus().equals(CompanyAccountStatusEnums.PASSED.name())){//审核通过修改存管账户同时修改用户中心的企业资料
				orgInfoReqDto=new OrganizationRequestDTO();
				reqDto.setCompanyName(response.getEnterpriseName());
				reqDto.setLegalPersonName(response.getLegal());
				reqDto.setLegalPersonIdCard(response.getLegalIdCardNo());
				reqDto.setBankLicence(response.getBankLicense());
				reqDto.setContactName(response.getContact());
				reqDto.setContactMobileNo(response.getContactPhone());
				reqDto.setAuditStatus(CompanyAccountStatusEnums.getByName(response.getReviewStatus()).getStatus());
				reqDto.setOrgNo(response.getOrgNo());
				reqDto.setBusinessLicense(response.getBusinessLicense());
				reqDto.setTaxNo(response.getTaxNo());
				reqDto.setUnifiedCode(response.getUnifiedCode());
				
				//修改用户中心企业资料
				orgInfoReqDto.setOrgNo(response.getOrgNo());
				orgInfoReqDto.setOrganizationName(response.getEnterpriseName());
				orgInfoReqDto.setRepresentative(response.getLegal());
				orgInfoReqDto.setAccountOpeningBankLicense(response.getBankLicense());
				orgInfoReqDto.setTaxId(response.getTaxNo());
				orgInfoReqDto.setUnifiedSocialCreditCode(response.getUnifiedCode());
				orgInfoReqDto.setCharterCode(response.getBusinessLicense());
				orgInfoReqDto.setCorporateContactsName(response.getContact());
				orgInfoReqDto.setContactsPhoneName(response.getContactPhone());
				orgInfoReqDto.setUpdateManager(1L);//系统修改默认id
				orgInfoReqDto.setUpdatetime(new Date());
				orgInfoReqDto.setLegalPersonCertNumber(response.getLegalIdCardNo());
				logger.info("修改企业资料回调处理###修改企业资料信息请求###request={}", JSON.toJSONString(orgInfoReqDto));
			}
			logger.info("修改企业资料回调处理###修改企业账户信息请求###request={}", JSON.toJSONString(reqDto));
			boolean isUpdateSuccess;
			try {
				isUpdateSuccess=accountCompanyDubboService.updateAccountCompany(reqDto);
				if(orgInfoReqDto!=null){
					if(isUpdateSuccess){
						AccountBaseResponse accountBaseResponse=accountDubboService.loadAccountByAccountNo(reqDto.getAccountNo());
						orgInfoReqDto.setId(accountBaseResponse.getOrgId());
						isUpdateSuccess=organizationDubboService.updateUserOrgInfo(orgInfoReqDto);
					}
				}
                logger.info("修改企业资料回调处理###修改响应###response={}", isUpdateSuccess);
            } catch (BizException e) {
                logger.error("修改企业资料回调处理###修改异常###errorCode={}, errorMessage={}", e.getErrorCode(), e.getMessage());
                throw e;
            } catch (Exception e) {
                logger.error(String.format("修改企业资料回调处理###未知异常###errorMessage=%s", e.getMessage()), e);
                throw new BizException("SYS9999");
            }
            HandleResult result = new HandleResult();
            result.setNeedAck(true);
            result.setData(Collections.singletonMap("orderStatus", isUpdateSuccess ? "SUCCESS" : "FAIL"));
            result.setRequestNo(response.getRequestNo());
            return result;
		}
		throw new BizException(response.getErrorCode(), response.getErrorMessage());
	}

	@Setter
	@Getter
	private static class BankCardMobileNoGatewayResponse {

		private static final String CALL_SUCCESS_CODE = "0";
		private static final String BUSINESS_SUCCESS_CODE = "SUCCESS";

		// 调用状态(0 为调用成功、1 为失败,返回 1 时请看【调用失败错误码】及错误码)
		private String code;

		// 业务处理状态(处理失败 INIT;处理成功 SUCCESS),平台可根据非 SUCCESS 状态做相应处理,处理失败时可参考错误码
		private String status;
		// 错误码
		private String errorCode;
		// 错误码
		private String errorMessage;
		// 平台用户编号
		private String platformUserNo;
		// 请求流水号
		private String requestNo;

		// 集团账户编号
		private String groupAccountNo;
        //审核状态(AUDIT表示审核中，PASSED表示审核通过，REFUSED表示审核拒绝)
		private String reviewStatus;
		//审核描述信息，审核拒绝会返回拒绝原因
		private String reviewDescription;
		//企业资质编码是否发生变更，YES变更，NO未变更
		private String qualificationModify;
		//变更后企业名称
		private String enterpriseName;
		//变更后开户银行许可证核准号
		private String bankLicense;
		//变更后组织机构代码
		private String orgNo;
		//变更后营业执照编码
		private String businessLicense;
		//变更后税务登记号
		private String taxNo;
		//变更后统一社会信用代码(可替代三证)
		private String unifiedCode;
		//变更后法人姓名
		private String legal;
		//变更后法人身份证
		private String legalIdCardNo;
		//变更后企业联系人
		private String contact;
		//变更后联系人手机号
		private String contactPhone;
       
		private boolean isCallSuccess() {
			return StringUtils.isNotBlank(code)&& CALL_SUCCESS_CODE.equals(code);
		}

		public boolean isBusinessSuccess() {
			return StringUtils.isNotBlank(status)&& BUSINESS_SUCCESS_CODE.equals(status);
		}

	}
}
